/**
 * 聊天面板组件
 * 对话式AI助手
 */

import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, Space, Avatar, Spin, message, Empty } from 'antd';
import {
  SendOutlined,
  RobotOutlined,
  UserOutlined,
  PlusOutlined,
  CopyOutlined,
} from '@ant-design/icons';
import type { ChatMessage } from '@/stores/copilot.store';
import './style.css';

const { TextArea } = Input;

interface ChatPanelProps {
  messages: ChatMessage[];
  loading?: boolean;
  onSendMessage: (message: string) => Promise<void>;
  onInsertMessage?: (messageId: string) => void;
  onClearHistory?: () => void;
}

export const ChatPanel: React.FC<ChatPanelProps> = ({
  messages,
  loading = false,
  onSendMessage,
  onInsertMessage,
  onClearHistory,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [sending, setSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const handleSend = async () => {
    if (!inputValue.trim()) {
      message.warning('请输入消息');
      return;
    }

    setSending(true);
    try {
      await onSendMessage(inputValue);
      setInputValue('');
    } catch (error) {
      console.error('Failed to send message:', error);
      message.error('发送失败，请重试');
    } finally {
      setSending(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleInsert = (messageId: string) => {
    if (onInsertMessage) {
      onInsertMessage(messageId);
      message.success('已插入到编辑器');
    }
  };

  const handleCopy = (content: string) => {
    navigator.clipboard.writeText(content);
    message.success('已复制到剪贴板');
  };

  return (
    <div className="chat-panel">
      {/* 消息列表 */}
      <div className="chat-messages">
        {messages.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="开始与AI助手对话"
          >
            <p className="chat-hints">你可以问我：</p>
            <ul className="chat-examples">
              <li>如何让这段文字更有说服力？</li>
              <li>帮我找一个相关的例子</li>
              <li>这段话应该如何改进？</li>
              <li>总结一下当前内容的要点</li>
            </ul>
          </Empty>
        ) : (
          <>
            {messages.map((msg) => (
              <div
                key={msg.id}
                className={`chat-message chat-message-${msg.role}`}
              >
                <div className="message-avatar">
                  {msg.role === 'user' ? (
                    <Avatar icon={<UserOutlined />} />
                  ) : (
                    <Avatar icon={<RobotOutlined />} style={{ backgroundColor: '#1890ff' }} />
                  )}
                </div>

                <div className="message-content">
                  <div className="message-bubble">
                    {msg.content.split('\n').map((line, index) => (
                      <p key={index}>{line}</p>
                    ))}
                  </div>

                  {msg.role === 'assistant' && (
                    <div className="message-actions">
                      <Space size="small">
                        <Button
                          type="text"
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => handleCopy(msg.content)}
                        >
                          复制
                        </Button>
                        {msg.canInsert && onInsertMessage && (
                          <Button
                            type="text"
                            size="small"
                            icon={<PlusOutlined />}
                            onClick={() => handleInsert(msg.id)}
                          >
                            插入到文章
                          </Button>
                        )}
                      </Space>
                    </div>
                  )}

                  <span className="message-time">
                    {new Date(msg.timestamp).toLocaleTimeString('zh-CN', {
                      hour: '2-digit',
                      minute: '2-digit',
                    })}
                  </span>
                </div>
              </div>
            ))}

            {loading && (
              <div className="chat-message chat-message-assistant">
                <div className="message-avatar">
                  <Avatar icon={<RobotOutlined />} style={{ backgroundColor: '#1890ff' }} />
                </div>
                <div className="message-content">
                  <div className="message-bubble message-loading">
                    <Spin size="small" />
                    <span style={{ marginLeft: 8 }}>AI正在思考...</span>
                  </div>
                </div>
              </div>
            )}

            <div ref={messagesEndRef} />
          </>
        )}
      </div>

      {/* 输入区域 */}
      <div className="chat-input-area">
        {messages.length > 0 && onClearHistory && (
          <div className="chat-actions">
            <Button
              type="text"
              size="small"
              onClick={onClearHistory}
            >
              清空对话
            </Button>
          </div>
        )}

        <Space.Compact style={{ width: '100%' }}>
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入消息... (Enter发送，Shift+Enter换行)"
            autoSize={{ minRows: 1, maxRows: 4 }}
            disabled={sending || loading}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={sending}
            disabled={!inputValue.trim() || loading}
          >
            发送
          </Button>
        </Space.Compact>
      </div>
    </div>
  );
};
